<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
            integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <style>
        #uploadImg{
            width: 400px;
            height: 300px;
        }
    </style>
</head>
<body>
<h1>文件上传</h1>
<hr>
<div>
    <form id="uploadForm" action="#" enctype="multipart/form-data">
        <table>
            <tr>
                <td class="title">上传照片：</td>
                <td><input type="file" id="file" name="file" value="选择图片" onchange="uploadFile()"/></td>
            </tr>
            <!--以下是实现图片预览-->
            <tr>
                <td colspan="2">
                    <img id="uploadImg" src="#"/>
                </td>
            </tr>
        </table>
    </form>
</div>

<script>
    //上传成功后的图片路径
    var uploadPath = "http://localhost:8080/uploaddemo/upload/";
    function uploadFile() {
        let formData = new FormData($('#uploadForm')[0]);
        $.ajax({
            type: 'post',
            url: "http://localhost:8080/uploaddemo/file/upload", //调用后台上传接口
            data: formData,
            cache: false,
            processData: false,
            contentType: false,
            success: function (data) {
                console.log(data);
                $('#uploadImg').attr("src",uploadPath+data.data);
            }
        });
    }

</script>
</body>
</html>
